'''
Created on Nov 29, 2009

@author: johnathon
'''

import NewNanobot

class CommunicationSystem():
    ''' This class is responsible for parsing the messages sent between
        individual Nanobots and interpreting them correctly. 
        Each method takes the Nanobot the received the communication
        and the communication itself (usually an object) as parameters
        and resolves them by performing the proper actions to the Nanobot
        and the message.
        This class is static among all Nanobots, but that is only for
        memory efficiency.
    '''
    
    def __init__(self):
        pass

    def sendMessage(self, recipient, function, message):
        ''' Sends a message to the recipient with the given message
            to be parsed with the given function
        '''
        recipient.incomingComms.append((function, message))
    
    def mergeMap(self, bot, map):
        ''' Merges the Nanobot's internalGrid with the otherBoard, such that each square
            reflects the most recently viewed condition.
        '''
        for i in range(0, bot.masterBoard.size):
            for j in range(0, bot.masterBoard.size):
                if bot.internalGrid[i][j].time > map[i][j].time:
                    map[i][j] = (bot.internalGrid[i][j]).copySquare()
                else:
                    bot.internalGrid[i][j] = (map[i][j]).copySquare()
                bot.internalGrid[i][j].copySquare()
                
    def mergeSet(self, bot1, data):
        ''' Merges a set of Data with another set of data supplied by another
            bot.
        ''' 
        bot2 = data[0]
        bot2prop = data[1]
        type = data[2]
        bot1prop = getattr(bot1, str(type))
        
        bot1prop = bot1prop | bot2prop
        # TODO: Not sure if this is necessary
        if len(bot1prop) > len(bot2prop):
            bot1.commSystem.sendMessage(bot2, bot1.commSystem.mergeSet, (bot1, bot1prop, type))
        
        setattr(bot1, str(type), bot1prop)
        
    def stopMovement(self, bot, data):
        ''' Makes the bot stop moving by emptying its actionQeueu '''
        try:
            del bot.actionQueue[:]
        except TypeError:
            pass
    
    def compareData(self, bot, data):
        ''' Sets the number of bots seen to the maximum of its current
            count and the number supplied
        '''
        bot.numBots = max(bot.numBots, data)
        
    def stateSet(self, bot, data):
        ''' Sets the bot's attribute with the same name as the string in data[0]
            to the value of data[1]s
        '''
        setattr(bot, data[0], data[1])
          